package org.example.judge_admin.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.judge_admin.entitry.RequestSessionParams;
import org.example.judge_admin.service.SessionService;
import org.example.judge_common.annotation.AuthAnnotation;
import org.example.judge_common.entity.PageResult;
import org.example.judge_common.entity.RequestParams;
import org.example.judge_common.entity.ResponseResult;
import org.example.judge_common.util.MyUtils;
import org.example.judge_pojo.Auth;
import org.example.judge_pojo.Session;
import org.example.judge_pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@CrossOrigin
@Slf4j
@RequestMapping("/user/session")
@RestController
public class SessionController {

    @Qualifier("SessionServiceImpl")
    @Autowired
    private SessionService sessionService;


    @PostMapping("/last")
    public ResponseResult getLast(String userId, HttpServletRequest request){
        if(MyUtils.isEmpty(userId)){
            User loginUser = (User) request.getAttribute("loginUser");
            userId = loginUser.getId();
        }
        Session session = sessionService.getLastOne(userId);
        if(session==null)return ResponseResult.success();
        if(MyUtils.isEmpty(session.getCity())){
            String ip = MyUtils.getIp(session.getIp());
            session.setCity(ip);
        }
        return ResponseResult.success().setData(session);
    }
    /**
     * 查询用户登录历史信息
     * @param params
     * @param request
     * @return
     */
    @PostMapping("/search")
    @AuthAnnotation({Auth.CLIENT,"User_Session"})
    @ResponseBody
    public ResponseResult session(RequestSessionParams params, HttpServletRequest request){
        User loginUser = (User) request.getAttribute("loginUser");
        if(MyUtils.isEmpty(params.getUserId())){

            params.setUserId(loginUser.getId());
        }
        if(!Auth.isAdmin(loginUser,"User_Session")&&!loginUser.getId().equals(params.getUserId()))return ResponseResult.unAuditor();
        PageResult<Session> res = sessionService.search(params);
        for (Session session : res.getDataList()) {
            if(MyUtils.isEmpty(session.getCity())){
                String ip = MyUtils.getIp(session.getIp());
                session.setCity(ip);
            }

        }
        return ResponseResult.success().setData(res);
    }
}
